#include "capturemanager.h"
#include "cvmanager.h"
#include "logger.h"

using namespace controllers;
using namespace utilities;

/**
 * @brief CaptureManager::CaptureManager
 */
CaptureManager::CaptureManager()
{
    _cameraIndex = 0;
    _cvCapture = cvCaptureFromCAM(_cameraIndex);
}

/**
 * @brief CaptureManager::CaptureManager
 * @param camIndex
 */
CaptureManager::CaptureManager(int camIndex)
{
    _cameraIndex = camIndex;
    _cvCapture = cvCaptureFromCAM(_cameraIndex);
}

/**
 * @brief CaptureManager::~CaptureManager
 */
CaptureManager::~CaptureManager()
{
    cvReleaseCapture(&_cvCapture);
}

/**
 * @brief CaptureManager::setCameraIndex
 * @param camIndex
 */
void CaptureManager::setCameraIndex(int camIndex)
{
    _cameraIndex = camIndex;
}

/**
 * @brief CaptureManager::getCameraIndex
 * @return
 */
int CaptureManager::getCameraIndex()
{
    return _cameraIndex;
}

/**
 * @brief CaptureManager::captureIplImage
 * @return
 */
IplImage* CaptureManager::captureIplImage()
{
    if (!_cvCapture)
    {
        Logger::logError("!!! CaptureManager::captureIplImage(): cvCaptureFromCAM");
        return NULL;
    }

    // Capture a frame
    IplImage* frame = cvQueryFrame(_cvCapture);

    if (frame == NULL)
    {
        Logger::logError("!!! CaptureManager::captureIplImage(): cvQueryFrame");
        return NULL;
    }

    return frame;
}

Mat* CaptureManager::captureMatImage()
{
    if (!_cvCapture)
    {
        Logger::logError("!!! CaptureManager::captureIplImage(): cvCaptureFromCAM");
        return NULL;
    }

    // Capture a frame
    IplImage* frame = cvQueryFrame(_cvCapture);

    if (frame == NULL)
    {
        Logger::logError("!!! CaptureManager::captureIplImage(): cvQueryFrame");
        return NULL;
    }

    return new Mat(frame);
}

/**
 * @brief CaptureManager::captureQImage
 * @return
 */
QImage CaptureManager::captureQImage()
{
    // Get a frame from the capture device
    IplImage *iplImage = captureIplImage();

    // Convert the IplImage object to a QImage object
    return CVManager::iplImageToQImage(iplImage);
}

/**
 * @brief CaptureManager::captureQImage
 * @return
 */
QImage CaptureManager::captureQImage(QSize size)
{
    // Get a frame from the capture device
    IplImage *iplImage = captureIplImage();

    // Convert the IplImage object to a QImage object of the specified size
    // Care is taken not to lose any aspect ratio
    return CVManager::iplImageToQImage(iplImage, size);
}
